<?php
	class Item implements JsonSerializable{
		private $id;
		private $name;
		private $recipes;
		private $base;

		private function __construct($id, $name, $base, $recipes = null)
		{
			$this->setId($id);
			$this->setName($name);
			$this->setRecipes($recipes);
			$this->base = $base;
		}

		// Public Methods
		function createBoM()
		{
			$list = new ItemList();
			$this->__createBoM($list);
			return $list;
		}

		public function jsonSerialize() {
			$arr = array(
				'id' => $this->getId(),
				'name' => $this->getName()
			);
			if(!empty($this->recipes)) $arr['recipes'] = $this->recipes;
			return $arr;
		}
		// End Public Methods

		// Getters / Setters
		function getName()
		{
			return $this->name;
		}

		private function setName($newName)
		{
			$this->name = $newName;
		}

		function getRecipes()
		{
			return $this->recipes;
		}

		private function setRecipes($newRecipes)
		{
			$this->recipes = $newRecipes;
		}

		function getId()
		{
			return (int)$this->id;
		}

		private function setId($newId)
		{
			$this->id = $newId;
		}
		// End Getters / Setters

		// Private Functions
		private function addRecipe(Recipe $recipe){
			if($this->recipes == null) $this->recipes = array();
			$this->recipes[] = $recipe;
			return $recipe;
		}

		private function __createBoM(ItemList &$list, $count = 1)
		{
			if (!$this->base) {
				$r = $this->recipes[0];	//HACK In case of multiple recipes, select the first one.
							//TODO Implement method to select the best recipe/let the user select the recipe
				foreach ( $r->getMaterials() as $mat ) {
					$mat->getItem()->__createBoM($list, $mat->getQuantity() * $count);
				}
			} else {
				$list->addItemStack(new ItemStack($this, $count));
			}
		}
		// End Private Functions

		// Static Methods
		public static function getItemForId($id, $addRecipe = false){
			$db = DbCfg::getConnection();

			$stmt = $db->prepare("select name, base from Item where itemid = ?");
			$stmt->execute(array($id));
			$res = $stmt->fetchObject();
			if($res) {
				$name = $res->name;
				$base = $res->base;
				$arr = null;
				if($addRecipe){
					$arr = array();
					$stmt = $db->prepare("select recipeid from Recipe where resultid=?");
					$stmt->execute(array($id));
					while(($res = (int)$stmt->fetchColumn()) != false){
						$arr[] = Recipe::getRecipeForId($res);
					}
				}
				return new Item($id, $name, $base, $arr);
			}
			else return null;
		}
		// End Static Methods
	}
?>
